import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStaticHandler, createStaticRouter, StaticRouterProvider } from 'react-router-dom/server';
import express from 'express';
import path from 'path';

import routes from './route/routes';
import createFetchRequest from './util/request';

const app = express();

app.use(express.static(path.resolve(__dirname + '/public')));

const handler = createStaticHandler(routes);

app.get('*', async (req, res) => {
  const fetchRequest = createFetchRequest(req, res);
  const context = await handler.query(fetchRequest);
  const router = createStaticRouter(handler.dataRoutes, context);
  const html = renderToString(<StaticRouterProvider router={router} context={context} />);
  res.send(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>with data</title>
    </head>
    <body>
        <div id="root">${html}</div>
        <script src="./main.client.js"></script>
    </body>
    </html>
    `);
});

const listener = app.listen(3000, () => {
  let { port } = listener.address();
  console.log(`Listening on port ${port}`);
});
